package cn.edu.zufe.mjt;

import java.lang.reflect.Field;

/**
 * @author 蒙锦涛
 * @date 2025/6/10
 */


public class Main {
	public static void main(String[] args) throws Exception {
		MyInterface proxy = MyInterfaceFactory.createProxy(new PrintFunctionName());
		proxy.func1();
		proxy.func2();
		proxy.func3();

		System.out.println("---------");
		proxy = MyInterfaceFactory.createProxy(new PrintFunctionName1());
		proxy.func1();
		proxy.func2();
		proxy.func3();


		System.out.println("---------");
		proxy = MyInterfaceFactory.createProxy(new LogHandler(proxy));
		proxy.func1();
		proxy.func2();
		proxy.func3();
	}

	static class PrintFunctionName implements MyHandler {
		@Override
		public String functionBody(String methodName) {
			return "\tSystem.out.println(\"" + methodName + "\");";
		}
	}

	static class PrintFunctionName1 implements MyHandler {
		@Override
		public String functionBody(String methodName) {
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.append("\tSystem.out.println(1);\n");
			stringBuilder.append("\t\tSystem.out.println(\"").append(methodName).append("\");");
			return stringBuilder.toString();
		}
	}

	static class LogHandler implements MyHandler {

		MyInterface myInterface;

		public LogHandler(MyInterface myInterface){
			this.myInterface = myInterface;
		}

		@Override
		public String functionBody(String methodName) {
			String context = "System.out.println(\"before\");\n" +
					"\t\tmyInterface." + methodName + "();\n" +
					"\t\tSystem.out.println(\"after\");";
			return context;
		}

		@Override
		public void setProxy(MyInterface proxy) {
			Class<? extends MyInterface> aClass = proxy.getClass();
			Field field = null;
			try {
				field = aClass.getDeclaredField("myInterface");
				field.setAccessible(true);
				field.set(proxy, this.myInterface);
			} catch (Exception e) {
				throw new RuntimeException(e);
			}
		}


	}

}
